package com.yuntoyun.fwcore.plug.tool;
/*
 * +----------------------------------------------------------------------
 * | @Author: codeavatar   @Year：2021
 * +----------------------------------------------------------------------
 * | @Email: codeavatar@aliyun.com
 * +----------------------------------------------------------------------
 */
import android.app.Activity;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

import androidx.annotation.ColorInt;
import androidx.fragment.app.FragmentActivity;

import com.yuntoyun.fwcore.plug.tool.ext.EmojiFilter;
import com.yuntoyun.fwcore.util.FwLogUtil;
import com.yuntoyun.fwcore.util.FwToastUtil;

/**
 * 组件工具类
 */
public class FwEditTextTool {

    private final String TAG = FwEditTextTool.class.getSimpleName();

    private static FwEditTextTool instance = null;

    public synchronized static FwEditTextTool builder() {
        if (null == instance) {
            instance = new FwEditTextTool();
        }
        return instance;
    }

    /**
     * 获取焦点
     *
     * @param editText
     */
    public void setFocus(final EditText editText) {
        if (null == editText) return;

        editText.setFocusable(true);//设置输入框可聚集
        editText.setFocusableInTouchMode(true);//设置触摸聚焦
        editText.requestFocus();//请求焦点
        editText.findFocus();//获取焦点
//        editText.setCursorVisible(true);
    }

    /**
     * 失去焦点
     *
     * @param editText
     */
    public void clearFocus(final EditText editText) {
        if (null == editText) return;

        editText.clearFocus();
//        editText.setCursorVisible(false);
    }

    /**
     * 设置Emojj表情过滤器
     *
     * @param editText
     */
    public void setEmojjFilter(final EditText editText) {
        if (null == editText) return;

        editText.setFilters(new InputFilter[]{new EmojiFilter()});
    }

    /**
     * 限制输入框值区间
     *
     * @param activity  当前活动
     * @param editText  输入框
     * @param minValue  最小值 null为不限
     * @param maxValue  最大值 null为不限
     * @param tipFormat 提示(为null，不提示）
     */
    public void setEditTextPriceRange(final Activity activity, final EditText editText,
                                      final Float minValue, final Float maxValue,
                                      final String tipFormat) {
        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    String txtValue = editText.getText().toString().trim();
                    if (TextUtils.isEmpty(txtValue)) {
                        return;
                    }
                    if (txtValue.endsWith(".")) {
                        txtValue = txtValue.replace(".", "");
                        editText.setText(txtValue);
                        if (null == minValue && null == maxValue) {
                            return;
                        }
                    }

                    float currentValue = Float.parseFloat(txtValue);
                    if (null != minValue && null != maxValue) {
                        float minVal = minValue.floatValue();
                        float maxValue = minValue.floatValue();
                        if (currentValue < minVal || currentValue > maxValue) {
                            FwToastUtil.builder().makeText(String.format(tipFormat,
                                    removeLastZero(minVal + ""), removeLastZero(maxValue + "")));
                        }
                    } else if (null != minValue) {
                        float minVal = minValue.floatValue();
                        if (minVal > currentValue) {
                            FwToastUtil.builder().makeText(String.format(tipFormat,
                                    removeLastZero(minVal + "")));
                            editText.setText(removeLastZero(minVal + ""));
                        }
                    } else if (null != maxValue) {
                        float maxVal = maxValue.floatValue();
                        if (maxVal < currentValue) {
                            FwToastUtil.builder().makeText(String.format(tipFormat,
                                    removeLastZero(maxVal + "")));
                            editText.setText(removeLastZero(maxVal + ""));
                        }
                    }
                }
            }
        });
    }

    /**
     * 清除小数点末尾为0
     *
     * @param val
     */
    public String removeLastZero(String val) {
        if (-1 != val.indexOf(".")) {
            val = val.replaceAll("0+?$", "");//去掉多余的0
            val = val.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        return val;
    }

    /**
     * 输入框内容长度监听
     *
     * @param activity
     * @param tvwInputTip
     * @param maxLength
     * @return
     */
    public TextWatcher getTextWatcher(FragmentActivity activity, TextView tvwInputTip,
                                      final int maxLength) {
        return this.getTextWatcher(activity, tvwInputTip, maxLength, Color.parseColor("#999999"),
                Color.parseColor("#FF0000"));
    }

    /**
     * 输入框内容长度监听
     *
     * @param activity
     * @param tvwInputTip
     * @param maxLength
     * @param defaultColorId
     * @param warnColorId
     * @return
     */
    public TextWatcher getTextWatcher(FragmentActivity activity, final TextView tvwInputTip,
                                      final int maxLength, @ColorInt final int defaultColorId,
                                      @ColorInt final int warnColorId) {
        if (null != tvwInputTip) {
            tvwInputTip.setText(String.format("%d/%d", 0, maxLength));
        }

        return new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int start, int before,
                                          int count) {
                //只要编辑框内容有变化就会调用该方法，s为编辑框变化后的内容
                FwLogUtil.info("onTextChanged", charSequence.toString());
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int count, int after) {
                FwLogUtil.info("beforeTextChanged", charSequence.toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {
                FwLogUtil.info("afterTextChanged", editable.toString());

                if (null == tvwInputTip) return;

                if (editable.length() > maxLength) {
                    editable.delete(maxLength, editable.length());
                }
                int num = editable.length();
                tvwInputTip.setText(String.format("%d/%d", num, maxLength));
                if (num >= maxLength) {
                    tvwInputTip.setTextColor(warnColorId);
                    FwToastUtil.builder().makeText("输入内容已达到字数限制！");
                } else {
                    tvwInputTip.setTextColor(defaultColorId);
                }
            }
        };
    }

    /**
     * 只能输入小数点后2位
     *
     * @param editText
     */
    public void setEditTextPricePoint(final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                FwLogUtil.info(TAG, "输入内容：" + s.toString());

                if (s.toString().startsWith(".")) {
                    //以.起始
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(s.length());
                } else if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
                if (s.toString().contains(".")) {
                    //包含.起始
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }

        });

        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    String txtValue = editText.getText().toString().trim();
                    if (!TextUtils.isEmpty(txtValue)) {
                        if (txtValue.endsWith(".")) {
                            txtValue = txtValue.replace(".", "");
                            editText.setText(txtValue);
                        }
                    }
                }
            }
        });
    }

    /**
     * 设置EditTextg光标位置
     *
     * @param editText
     * @return
     */
    public void setEditTextSelection(EditText editText, int length) {
        editText.setSelection(length);
    }

    /**
     * 批量绑定文本框清空按扭
     *
     * @param ettList
     * @param ivwList
     */
    public void setEditTextBindClearList(List<EditText> ettList, List<ImageView> ivwList) {
        for (int i = 0; i < ettList.size(); i++) {
            if (null == ettList.get(i) || null == ivwList.get(i)) {
                return;
            }
            setEditTextBindClear(ettList.get(i), ivwList.get(i), null);
        }
    }

    /**
     * 绑定文本框清空按扭
     *
     * @param ett
     * @param ivw
     */
    public void setEditTextBindClear(final EditText ett, final ImageView ivw, final IEditClearCallback callback) {
        if (null == ett || null == ivw)
            return;

        ivw.setVisibility(View.GONE);
        ivw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ett.setText("");
                if (null != callback) {
                    callback.clearCallback();
                }
            }
        });

        ett.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                FwLogUtil.info(TAG, "输入内容：" + s.toString());
                if (s.toString().trim().length() < 1) {
                    ivw.setVisibility(View.GONE);
                } else {
                    ivw.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    //回调事件

    public interface IEditClearCallback {
        void clearCallback();
    }
}
